<?php
/*********************************************************************/
// Project : QLDA
//-------------------------------------------------------------------//
// Module  : Components
//-------------------------------------------------------------------//
// File    :  file.php
//-------------------------------------------------------------------//
// Charset : UTF-8
//-------------------------------------------------------------------//
// Memo    :
//-------------------------------------------------------------------//
// Version : Add ( tuanna )  ( 27/10/2008 )
/*********************************************************************/
class FileComponent extends Component
{
    var $controller;
    var $split = "___";
    var $Common = null;

    /**
     * Image rotate
     *
     * @param string - full path
     * @param int  - degree need to rotate
     * @return type  meta
     * @access public
     */
    function image_rotate($filename, $degrees) {
        // Load
        $source = imagecreatefromjpeg($filename);

        // Rotate
        $rotate = imagerotate($source, $degrees, 0);

        // Output
        return imagejpeg($rotate, $filename);
    }


    /**@brief Save file to server
 *
 * @param $fileData
 * @param $fileName
 * @param $folder
 */
    //***************************************************************//
    // Function : upload
    //---------------------------------------------------------------//
    // Params   :
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) ( Sep 26, 2008 )
    //***************************************************************//
    function upload( $fileData, $fileName = null, $folder = PUBLIC_IMAGE_DETAIL )
    {
        APP::import( "Component", "Common" );
        $this->Common =& new CommonComponent( );

        if( empty($fileData['tmp_name'] ) || $fileData['error'] != 0 ) return false;

		if( !is_dir( $folder ) )
        {
            mkdir( $folder );
            chmod($folder, 0777);
        }

        // tao file tmp
        if( strlen( $fileName ) == 0 )
        {
        	$tmp = $fileData["name"];
            $ext = substr( $tmp, -4 );

			// Truong hop duoi co 4 ki tu (xlsx)
            if( !strpos($ext, '.') )
            {
				$ext = substr( $fileData["name"], -5 );
				$fileData["name"] = substr( $fileData["name"], 0, strlen( $fileData["name"] ) - 5  );
            }
            else // Truong hop duoi co 4 ki tu (xls)
            {
            	$ext = substr( $fileData["name"], -4 );
            	$fileData["name"] = substr( $fileData["name"], 0, strlen( $fileData["name"] ) - 4  );
            }

            $fileData["name"] = $this->Common->_SEO( $fileData["name"] ) . $ext;

            $fileName = intval(mt_rand()) . $this->split . preg_replace( "/\s+/", "_", $fileData["name"] );
        }

        if ( is_uploaded_file( $fileData['tmp_name'] ) )
        {
            $file = $folder . $fileName;

            if( copy( $fileData['tmp_name'], $file ) )
            {
               //$exif = $this->getExif( $file );

                chmod( $file  , 0777 );
            } else {
                return false;
            }

            return str_replace('\\', '/', str_replace( $folder, "", $file ));

        } else {
            return false;
        }
    }

    /**
     * Download file from internet
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
      function getFileFromUrl($url, $folder = TMP_IMAGE)
    {
        if( empty($url) ) return "";

        $content = @file_get_contents( $url );

        $folder1 = $folder .  substr(md5(  basename($url) ), 0, 3);

         if( !is_dir( $folder1 ) )
        {
            mkdir( $folder1 );
            chmod($folder1, 0777);
        }


        $file = $folder1 . '/' . date('ymdhis') .  $this->split . basename($url);

        // kiem tra file ton tai
        if( !file_exists( $file ) )
        {
            $f = fopen(  $file, 'w' );
            fwrite( $f, $content );
            fclose($f);

            return str_replace("\\", '/', str_replace( $folder, "", $file ));
        }
        else
        {
            return "";
        }
    }

    //***************************************************************//
    // Function :
    //---------------------------------------------------------------//
    // Params   :
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( SONY ) ( Nov 4, 2008 )
    //***************************************************************//
    function move( $source_file = null, $dest_folder = null )
    {
        // check exist dir
        if( !is_dir($dest_folder ) )
        {
            mkdir( $dest_folder, 0777, true );
        }

        // check dieu kien vao
        if( file_exists( $source_file ) == false
        || is_dir( $dest_folder ) == false
        || is_writable( $dest_folder ) == false )
        {
            return false;
        }

        $new_file = $dest_folder . DS . basename( $source_file );
        // copy file to new location
        copy( $source_file,  $new_file );
        chmod( $new_file, 0777 );
        unlink( $source_file );
        return true;

    }

    //***************************************************************//
    // Function :
    //---------------------------------------------------------------//
    // Params   :
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( SONY ) ( Nov 4, 2008 )
    //***************************************************************//
    function get_file_type( $file  = null )
    {
        if( file_exists( $file ) == true )
        {
            return exec( 'file -b ' . escapeshellarg ( $file ), $a ) ;
        }
        else
        {
            return null;
        }

    }
    //***************************************************************//
    // Function : _get_extension
    //---------------------------------------------------------------//
    // Params   : file name
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) ( Oct 27, 2008 )
    //***************************************************************//
    function _get_extension( $filename = "" )
    {
        $ext = '';
        $array = split( "\.", $filename );
        $count = count( $array );

        if( $count > 1 )
        {
            $ext = $array[$count - 1];
        }
        else
        {
            $ext = "";
        }

        return $ext;
    }

    //***************************************************************//
    // Function : _get_resize
    //---------------------------------------------------------------//
    // Params   : $width (i)
    //          : $height(i)
    //          : $scale (i)
    //---------------------------------------------------------------//
    // Return   : array(  $width, $height )
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( SONY ) ( Aug 6, 2008 )
    //***************************************************************//
    function _get_resize( $width, $height, $scale = 0.25 )
    {
        $array = array( );
        if( is_numeric( $width ) == true
        && is_numeric( $height ) == true )
        {
            $array = array( round( $width * $scale, 0 ),
                            round( $height * $scale, 0 ) );
        }

        return $array;
    }

    function _create_file_name_without_ext( )
    {
        $filename = date("YmdHis" . rand( 1000, 9999 ) );
        return $filename;
    }

    function _check_exist_file( $filename = null )
    {
        return file_exists( $filename );
    }

    function _get_image_size( $filename = null )
    {
        return getimagesize($filename);
    }

    function _create_tmp_image( $width  = 100, $height = 100)
    {
        if( is_numeric( $width ) == false
        || is_numeric( $height ) == false )
        {
            return null;
        }

        $image = imagecreatetruecolor( $width, $height );
        return $image;
    }

//    function _get_file_type( )
//    {

//    }
    //***************************************************************//
    // Function : _can_resize
    //---------------------------------------------------------------//
    // Params   : $filename (i)
    //---------------------------------------------------------------//
    // Return   : true / false
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( SONY ) ( Aug 6, 2008 )
    //***************************************************************//
    function _can_resize( $filename = null )
    {
        $resource = false;

        switch($this->_get_extension( strtolower($filename ) ) )
        {
            case 'jpg':
            case 'jpeg':
                $resource = true;
                break;

            case 'gif':
                $resource = true;
                break;

            case 'png':
                $resource = true;
                break;
        }

        return $resource;
    }

    //***************************************************************//
    // Function : _get_image
    //---------------------------------------------------------------//
    // Params   :
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) ( Oct 27, 2008 )
    //***************************************************************//
    function _get_image( $filename = null )
    {
        $resource = false;

        switch($this->_get_extension( strtolower($filename ) ) )
        {
            case 'jpg':
            case 'jpeg':
                $resource = imagecreatefromjpeg( $filename );
                break;

            case 'gif':
                $resource = imagecreatefromgif( $filename );
                break;

            case 'png':
                $resource = imagecreatefrompng( $filename );
                break;

            //add : sonmtt
            case 'pdf':
                $resource = imagecreatefrompng( $filename );
                break;
        }

        return $resource;
    }

    //***************************************************************//
    // Function : _get_file_name
    //---------------------------------------------------------------//
    // Params   : $object (i) for 1 uploaded or a number for many file
    //---------------------------------------------------------------//
    // Return   : file name
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( SONY ) ( Aug 5, 2008 )
    //***************************************************************//
    function _get_file_name( $fileData = null, $id = null )
    {
        if( is_array( $fileData ) == true )
        {
            $filename = $fileData["tmp_name"];
        }
        else
        {
            $filename = $fileData["tmp_name"][$id];
        }

        return $filename;
    }

    /**
     * Remove thumbs files
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function remove_thumb($file)
    {
        // remove web thumbs
        @unlink( PUBLIC_IMAGE_THUMB . $file );

        // remove wap thumbs
        @unlink( PUBLIC_IMAGE_DETAIL. $file );

        //@unlink( TMP_IMAGE . $file);
    }

    /**
     * Create thumbnail for web, mobile and wap
     * @param - $file : file
     */

    function create_thumb( $fileName, $path = PUBLIC_IMAGE_DETAIL, $sub = null )
    {
        // Create for Web
        $this->resize( $fileName, $path, PUBLIC_IMAGE_THUMB . $sub, THUMB_WIDHT, THUMB_HEIGHT );
        //$this->resize( $fileName, $path, PUBLIC_IMAGE_CATEGORY . $sub, CATEGORY_WIDHT, CATEGORY_HEIGHT );
        //$this->resize( $fileName, $path, PUBLIC_IMAGE_SLIDE . $sub, SLIDE_WIDHT, SLIDE_HEIGHT );
        //$this->resize( $fileName, $path, PUBLIC_IMAGE_DETAIL . $sub, DETAIL_WIDHT, DETAIL_HEIGHT );
    }

    /**
     * Create thumbnail for web, mobile and wap
     * @param - $file : file
     */
    function resize( $filename = null, $source , $dest, $width = 100, $height = 100 )
    {
        // solve file name
        if( substr($source, strlen( $source) - 1, 1 ) != '/' )
            $source .= '/';

        if( substr($dest, strlen( $dest) - 1, 1 ) != '/' )
            $dest .= '/';

        $large_file = $source . $filename;
        $small_file = $dest . $filename;

        if( $this->_can_resize( $large_file ) == false )
        {
            return false;
        }

        $path = dirname( $small_file );
        if( !is_dir( $path ) )
        {
            mkdir( $path, 0777, true );
        }

        // get image size
        list( $old_width, $old_height ) =
                          $this->_get_image_size( $large_file );

        $scale1 = 1;

        if( $width >= $height )
        {
            $scale = $width / $old_width;
        }
        else
        {
            $scale = $height / $old_height;
        }

        $width = $scale * $old_width;
        $height = $scale * $old_height;

        // create temp image
        $tmp_image = $this->_create_tmp_image( $width, $height );

        $result = false;
        if( empty( $tmp_image ) == false )
        {
            // get real image
            $image = $this->_get_image( $large_file );

            if( is_null( $image ) == false  )
            {
                // resize image
                imagecopyresampled( $tmp_image, $image, 0, 0, 0, 0,
                           $width, $height, $old_width, $old_height );

               // write into file
               imagejpeg( $tmp_image, $small_file, 100 );

               chmod( $small_file, 0777 );
               $result = true;
            }
        }

        return $result;
    }

    //***************************************************************//
    // Function : check_extension
    //---------------------------------------------------------------//
    // Params   : $filedata: mang luc upload len
    //              $ext: cac extension file muon check
    //                  $type: loai file can check,
    //      vd type =:application/octet-stream : file *.mp3, *.wma
    //              =:text/plain; charset=us-ascii : file *.xml
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) ( Oct 30, 2008 )
    //***************************************************************//
    function check_extension( $filedata = array( ), $ext = array( "jpg", "bmp", "gif", "png" ), $types = null )
    {
        //namnb: them vao kiem tra loai file, du doi duoi ext cung bat duoc
        if( is_array( $types ) )
        {
            $type_file = $this->get_file_type( $filedata['tmp_name'] );
            $type_file = strtolower( $type_file );
            $arr = split( '[\-\/\ \:]', $type_file );

            //kiem tra xem co bat ki phan tu nao trong chuoi thuoc mang hay ko
            $check_type = FALSE;
            foreach( $arr as $key => $value )
            {
              if( in_array( strtolower( $value ), $types ) == TRUE )
              {
                  $check_type = TRUE;
                      break;
              }

            }

            if( $check_type == FALSE )
            {
              return FALSE;
            }
        }
        //namnb: ---------end------------------------------------------

        if( is_array( $filedata ) == true  )
        {
            $arr = split( "\.", $filedata["name"] );
            return in_array( strtolower( $arr[count( $arr ) -1] ), $ext );
        }
        return false;
    }
    //***************************************************************//
    // Function :
    //---------------------------------------------------------------//
    // Params   :
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( SONY ) ( Nov 14, 2008 )
    //***************************************************************//
    function print_file( $filename  )
    {

        if( file_exists( $filename ) )
        {
            header("Content-Type: application/octet-stream");
            header("Content-Disposition: inline");
            header("Content-Description: File Transfer");
            header("Content-Length: " . filesize($filename));
             // xuat noi dung file
             flush(); // this doesn't really matter.

            $fp = fopen($filename, "r");
            while (!feof($fp))
            {
                echo fread($fp, 65536);
                flush(); // this is essential for large downloads
            }
            fclose($fp);
             exit;
        }

        header("HTTP/1.0 404 Not Found");
        exit;
    }

    //***************************************************************//
    // Function : mkdir
    //---------------------------------------------------------------//
    // Params   : pathname : duong dan can tao thu muc
    //---------------------------------------------------------------//
    // Return   : true/false
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( namnb ) ( Aug 26, 2008 )
    //***************************************************************//
    function mk_dir( $pathname )
    {
        //Neu duong dan nay la mot thu muc thi chung to thu muc da ton tai
        if( is_dir( $pathname ) == TRUE )
        {
            //is_dir returns TRUE if the filename exists and is a directory, FALSE otherwise.
            //neu da ton tai thi change mode
            //return chmod( $pathname, 0777 );
            return true;
        }
        return ( mkdir( $pathname ) && chmod( $pathname, 0777 ) );
    }

    /**
     * Get Exif
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function getExif($file) {
        // auto rotate the image

        //$exif = @exif_read_data($file);
        $exif = null;

        if( !empty( $exif )  && isset( $exif['Orientation'] ) )
        {
            $ort = $exif['Orientation'];

            require_once(  APP . 'Vendor' . DS . 'wideimage-11.02.19/lib/WideImage.php' );

            $image = WideImage::load($file);

            $image = WideImage_Operation_ExifOrient::execute( $image, $ort );
            $image->saveToFile($file);

            // GD doesn't support EXIF, so all information is removed.
            // $image->exifOrient($ort)->saveToFile($file);

            // get GPS
            if( !empty( $exif['GPS']['GPSLatitude'] ) )
            {
                $lat_ref = $exif['GPS']['GPSLatitudeRef'];
                $lat = $exif['GPS']['GPSLatitude'];
                list($num, $dec) = explode('/', $lat[0]);
                $lat_s = $num / $dec;
                list($num, $dec) = explode('/', $lat[1]);
                $lat_m = $num / $dec;
                list($num, $dec) = explode('/', $lat[2]);
                $lat_v = $num / $dec;

                $lon_ref = $exif['GPS']['GPSLongitudeRef'];
                $lon = $exif['GPS']['GPSLongitude'];
                list($num, $dec) = explode('/', $lon[0]);
                $lon_s = $num / $dec;
                list($num, $dec) = explode('/', $lon[1]);
                $lon_m = $num / $dec;
                list($num, $dec) = explode('/', $lon[2]);
                $lon_v = $num / $dec;

                $gps_int = array($lat_s + $lat_m / 60.0 + $lat_v / 3600.0, $lon_s
                        + $lon_m / 60.0 + $lon_v / 3600.0);
                $exif['GPS']['location'] =  $gps_int;
            }
        }

        return $exif;
    }
}


class WideImage_Operation_ExifOrient
{
  /**
   * Rotates and mirrors and image properly based on current orientation value
   *
   * @param WideImage_Image $img
   * @param int $orientation
   * @return WideImage_Image
   */
  static function execute($img, $orientation)
  {
    switch ($orientation) {
      case 2:
        return $img->mirror();
        break;

      case 3:
        return $img->rotate(180);
        break;

      case 4:
        return $img->rotate(180)->mirror();
        break;

      case 5:
        return $img->rotate(90)->mirror();
        break;

      case 6:
        return $img->rotate(90);
        break;

      case 7:
        return $img->rotate(-90)->mirror();
        break;

      case 8:
        return $img->rotate(-90);
        break;

      default: return $img->copy();
    }
  }
}
?>